package com.sts.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sts.config.UploadProperties;
import com.sts.dto.AttachmentDTO;
import com.sts.dto.AttachmentUploadDTO;
import com.sts.entity.Attachment;
import com.sts.mapper.AttachmentMapper;
import com.sts.service.AttachmentService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;


@Service
@RequiredArgsConstructor
public class AttachmentServiceImpl implements AttachmentService {

    private final AttachmentMapper attachmentMapper;
    private final UploadProperties uploadProperties;
    @Override
    @Transactional
    public AttachmentDTO upload(AttachmentUploadDTO dto, Long uploaderId) {
        MultipartFile file = dto.getFile();
        String originalName = file.getOriginalFilename();
        String suffix = FileUtil.getSuffix(originalName);
        String newFileName = IdUtil.fastSimpleUUID() + "." + suffix;

        // 1. 真实目录：D:/sts-upload/2025/09/05/
        Path dateDir = uploadProperties.getPath()
                .resolve(LocalDateTime.now().toLocalDate().toString().replace("-", "/"));
        try {
            Files.createDirectories(dateDir);
        } catch (IOException e) {
            throw new RuntimeException("创建目录失败", e);
        }

        Path dest = dateDir.resolve(newFileName);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            throw new RuntimeException("文件保存失败", e);
        }

        // 2. 存相对路径，方便以后迁移
        String relativePath = uploadProperties.getPath().relativize(dest).toString().replace("\\", "/");

        Attachment entity = Attachment.builder()
                .ticketId(dto.getTicketId())
                .commentId(dto.getCommentId())
                .fileName(originalName)
                .filePath(relativePath)
                .fileSize(file.getSize())
                .fileType(suffix)
                .uploaderId(uploaderId)
                .createdAt(LocalDateTime.now())
                .build();
        attachmentMapper.insert(entity);
        return BeanUtil.copyProperties(entity, AttachmentDTO.class); }

    @Override
    public List<AttachmentDTO> listByTicket(Long ticketId) {
        LambdaQueryWrapper<Attachment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Attachment::getTicketId, ticketId).orderByDesc(Attachment::getCreatedAt);
        return attachmentMapper.selectList(wrapper)
                .stream().map(e -> BeanUtil.copyProperties(e, AttachmentDTO.class))
                .collect(Collectors.toList());
    }

    @Override
    public List<AttachmentDTO> listByComment(Long commentId) {
        LambdaQueryWrapper<Attachment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Attachment::getCommentId, commentId).orderByDesc(Attachment::getCreatedAt);
        return attachmentMapper.selectList(wrapper)
                .stream().map(e -> BeanUtil.copyProperties(e, AttachmentDTO.class))
                .collect(Collectors.toList());
    }

    @Override
    public void delete(Long id, Long operatorId) {
        // 如需权限校验可扩展
        attachmentMapper.deleteById(id);
    }
}